package org.kugua.processor.impl;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.kugua.context.CaptchaContext;
import org.kugua.image.ImageSelector;
import org.kugua.image.impl.MemoryBgImageSelector;
import org.kugua.processor.IPreProcessor;
import org.kugua.utils.ImageUtils;
import org.kugua.utils.RandomUtils;

import java.awt.image.BufferedImage;

/**
 * BackgroundImageProcessor
 *
 * @author 苦瓜
 * @create 2024-08-27
 * @since 1.0.0
 */
@Setter
@Getter
@Slf4j
public class BackgroundImageProcessor implements IPreProcessor {

    private ImageSelector<BufferedImage> imageSelector = new MemoryBgImageSelector();

    /**
     * 前置处理
     *
     * @param context 上下文
     */
    @Override
    public void process(CaptchaContext context) {
        BufferedImage image = imageSelector.select();
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();
        int captchaWidth = context.getWidth();
        int captchaHeight = context.getHeight();
        log.trace("BackgroundImageProcessor PreProcess. imageWidth:{}, imageHeight:{}," +
                        " captchaWidth:{}, captchaHeight:{}",
                imageWidth, imageHeight, captchaWidth, captchaHeight);
        if (imageWidth < captchaWidth || imageHeight < context.getHeight()) {
            log.trace("the image size does not meet the requirements.");
            return;
        }
        BufferedImage bufferedImage = ImageUtils.scaleImage(image, captchaWidth, captchaWidth);
        context.getGraphics().drawImage(bufferedImage, 0, 0, captchaWidth, captchaHeight, null);
    }
}
